import React, { useState, useRef, useEffect } from 'react'
import { useModel } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import { App, Button, Form, Input, Popconfirm, Space, Radio, Drawer, Select, Alert, Image } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { copyLink } from '@/utils/utils'
import PromotionOrderDetails from './PromotionOrderDetails/PromotionOrderDetails'
import dayjs from 'dayjs'
import PromotionLinkModal from '@/components/PromotionLinkModal'
import './H5Promotion.less'
const { Option } = Select

const tabObj = {
  'mp-alipay': 1,
  'mp-weixin': 2,
  app: 3,
  h5: 4
}

export default ({ pageType, pageId }) => {
  const {
    PromotionList,
    DelPromotionInfo,
    GetPromotionPage,
    UpdatePromotionInfo,
    AddPromotionLink,
    SetLinkStatus,
    GetPromotionInfo
  } = useModel('H5Promotion')

  const { PlatformGoodsList, GetShipTypes } = useModel('Coupon')

  const { GetShopSelections, GetShowPlts } = useModel('Goods')

  const { GetChannels, setIsLoading, platformInfo } = useModel('Global')

  const { message, modal } = App.useApp()

  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [currentPage, setCurrentPage] = useState(1) //  当前页码

  const tableRef = useRef()
  const [addAndEditModalFormRef] = Form.useForm()

  const [channelList, setChannelList] = useState([]) // 渠道列表
  const [drawerOpen, setDrawerOpen] = useState(false) // 订单数据抽屉
  const [drawerData, setDrawerData] = useState({}) // 订单数据抽屉数据

  const [currentIsOpen, setCurrentIsOpen] = useState(false) // 是否是开放数据

  const [promotionModalOpen, setPromotionModalOpen] = useState(false) // 推广弹窗

  const [promotionPageMap, setPromotionPageMap] = useState({}) // 推广页面 map

  const [userParams, setUserParams] = useState({}) // 传递给推广链接的参数

  const [drawerSelectGoods, setDrawerSelectGoods] = useState([]) // 选择的商品
  const [goodsDrawerFlag, setGoodsDrawerFlag] = useState(false) // 商品抽屉
  const [shopList, setShopList] = useState([]) // 店铺列表
  const [shipList, setShipList] = useState([]) // 物流配送
  const [searchChannel, setSearchChannel] = useState([]) // 展示渠道
  const selectGoodsTableRef = useRef()
  const [tempChannel, setTempChannel] = useState('mp-alipay') // 临时渠道

  useEffect(() => {
    if (pageType === 'open') setCurrentIsOpen(true)
    getChannelList()
    getPromotionPageMap()
  }, [])

  // 获取渠道列表
  const getChannelList = async () => {
    const res = await GetChannels()
    if (res) {
      setChannelList(res)
    }
  }

  // 获取推广页面 map
  const getPromotionPageMap = async () => {
    const res = await GetPromotionPage()
    if (res) {
      setPromotionPageMap(res)
    }
  }

  // 删除
  const handleDeleteItem = async row => {
    const res = await DelPromotionInfo({ id: row.id })
    if (res) {
      tableRef.current.reload()
      message.success('删除成功')
    }
  }

  // 停用/启用
  const handleSetStatus = async row => {
    const res = await SetLinkStatus({ id: row.id })
    if (res) {
      tableRef.current.reload()
      message.success('操作成功')
    }
  }

  // 添加/修改
  const handleAddAndEdit = async (type, row) => {
    if (type === 'edit') {
      setIsLoading(true)
      // 获取详情
      const res = await GetPromotionInfo({ id: row.id })

      if (res) {
        addAndEditModalFormRef.setFieldsValue({
          ...res,
          promotion_name: res.plat_from
        })
      }

      setTempChannel(res.channel)

      setIsLoading(false)
    }

    // 添加/修改弹窗
    const AddAndEditModal = () => {
      return (
        <Form
          preserve={false}
          style={{ paddingTop: 20 }}
          form={addAndEditModalFormRef}
          name='addAndEditModal'
          initialValues={{
            channel: channelList[0].label,
            page_type: 1
          }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
        >
          <Form.Item name='promotion_name' label='名称' rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder='请输入名称' allowClear />
          </Form.Item>

          <Form.Item
            extra='选择需要投放的渠道分类'
            name='channel'
            label='渠道类型'
            rules={[{ required: true, message: '请选择渠道类型' }]}
          >
            <Radio.Group
              onChange={value => {
                addAndEditModalFormRef.setFieldsValue({
                  // 推广界面
                  page_type: 1,
                  // 商品
                  goods_id: '',
                  goods_name: '',
                  goods_cover_url: '',
                  // 备注
                  remark: ''
                })

                setTempChannel(value.target.value)
              }}
            >
              {channelList.map((item, index) => {
                return (
                  <Radio value={item.label} key={index}>
                    {item.name}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>

          <Form.Item name='page_type' label='推广页面' rules={[{ required: true, message: '请选择推广页面' }]}>
            <Select placeholder='请选择推广页面' allowClear>
              {Object.keys(promotionPageMap).map(key => {
                return (
                  <Option value={Number(key)} key={key}>
                    {promotionPageMap[key].text}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>

          <Form.Item shouldUpdate noStyle>
            {() => {
              let isGoods = addAndEditModalFormRef.getFieldValue('page_type') === 3
              return (
                <>
                  {isGoods ? (
                    <Form.Item
                      name='goods_id'
                      label='商品'
                      colon={false}
                      rules={[{ required: true, message: '请选择商品' }]}
                    >
                      {addAndEditModalFormRef.getFieldValue('goods_id') ? (
                        <div className='select_goods_card'>
                          <Image
                            height={100}
                            width={100}
                            src={addAndEditModalFormRef.getFieldValue('goods_cover_url')}
                          />
                          <div className='goods_name'>{addAndEditModalFormRef.getFieldValue('goods_name')}</div>
                        </div>
                      ) : null}

                      <Button type='primary' ghost onClick={() => handleSelectGoods()}>
                        {addAndEditModalFormRef.getFieldValue('goods_id') ? '更改商品' : '选择商品'}
                      </Button>
                    </Form.Item>
                  ) : null}
                </>
              )
            }}
          </Form.Item>

          <Form.Item name='remark' label='备注'>
            <Input.TextArea placeholder='请输入备注' allowClear />
          </Form.Item>
        </Form>
      )
    }

    modal.confirm({
      title: type === 'edit' ? '编辑' : '新增' + '推广链接',
      width: 600,
      icon: null,
      content: channelList ? <AddAndEditModal /> : null,
      destroyOnClose: true,
      onOk: async () => {
        await addAndEditModalFormRef.validateFields()
        let params = addAndEditModalFormRef.getFieldsValue()
        // params.share_link = platformInfo.h5_url

        // console.log('params========', params)

        const res =
          type === 'edit'
            ? await UpdatePromotionInfo({
                id: row.id,
                ...params
              })
            : await AddPromotionLink(params)
        if (res) {
          tableRef.current.reload()
          message.success('操作成功')
        }
      }
    })
  }

  // 获取展示渠道
  const getDisplayChannels = async () => {
    const res = await GetShowPlts()
    if (res) {
      let arr = []
      // eslint-disable-next-line guard-for-in
      for (const resKey in res) {
        arr.push({
          id: resKey,
          value: res[resKey]
        })
      }
      arr && setSearchChannel(arr.map(i => [i.id, i.value]))
    }
  }

  //  获取物流配送
  const getShopList = async () => {
    const res = await GetShopSelections()
    if (res) {
      setShopList(res.map(i => [i.id, i.shop_name]))
    }
  }

  // 获取店铺列表
  const getShipSelection = async () => {
    let res = await GetShipTypes()
    if (res) {
      setShipList(res.map(i => [i.key, i.value]))
    }
  }

  // 选择商品
  const handleSelectGoods = () => {
    getShipSelection() // 获取店铺列表
    getShopList() // 获取物流配送
    getDisplayChannels() // 获取展示渠道

    // 回显数据
    const row = addAndEditModalFormRef.getFieldsValue()
    setDrawerSelectGoods([
      {
        ...row,
        id: row.goods_id
      }
    ])

    triggerGoodsDrawer()
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  // 查看详情
  const handleCheckDetail = async (type, row) => {
    let channelType = {
      order: {
        title: '转换订单明细',
        type: 0
      },
      deal: {
        title: '成交订单明细',
        type: 1
      },
      deal_user: {
        title: '成交用户订单明细',
        type: 2
      },
      overdue_order: {
        title: '逾期订单明细',
        type: 3
      }
    }

    setDrawerData({
      title: channelType[type].title,
      type: channelType[type].type,
      type_map: type,
      currentIsOpen,
      ...row
    })

    onDrawerChange()
  }

  // 开放数据
  const handleOpenData = async row => {
    copyLink(encodeURI(`${window.location.origin}/openPlatform/${row.id}`))
  }

  // 推广链接
  const handlePromotionLink = async row => {
    setIsLoading(true)
    const paramsPageType = promotionPageMap[row.page_type].page_type
    const pageParams = {}

    const res = await GetPromotionInfo({ id: row.id })

    if (res) {
      // 商品详情
      if (paramsPageType === 'goodsDetail') {
        pageParams.id = res.goods_id
      }

      pageParams.global_promotionid = row.id // 全局推广 id

      setUserParams({
        page_type: paramsPageType,
        channel: row.channel,
        pageParams
      })

      setPromotionModalOpen(true)
    }

    setIsLoading(false)
  }

  // 订单数据抽屉
  const onDrawerChange = () => {
    setDrawerOpen(!drawerOpen)
  }

  // 开关商品抽屉
  const triggerGoodsDrawer = () => {
    setGoodsDrawerFlag(!goodsDrawerFlag)
  }

  // 处理商品抽屉选择商品
  const handleDisplay = async () => {
    if (!drawerSelectGoods.length) {
      message.warning('请最少选择一个商品')
      return
    }

    console.log('drawerSelectGoods========', drawerSelectGoods)

    addAndEditModalFormRef.setFieldsValue({
      goods_id: drawerSelectGoods[0].id,
      goods_name: drawerSelectGoods[0].goods_name,
      goods_cover_url: drawerSelectGoods[0].goods_cover_url
    })

    setDrawerSelectGoods([])
    triggerGoodsDrawer()
  }

  // 常规页面
  const originColumns = [
    {
      title: '名称',
      dataIndex: 'promotion_name',
      align: 'center',
      width: 100
    },
    {
      title: '渠道分类',
      dataIndex: 'channel',
      align: 'center',
      width: 100,
      valueType: 'select',
      valueEnum: () => {
        let channelObj = {}
        // eslint-disable-next-line array-callback-return
        channelList.map(item => {
          channelObj[item.label] = {
            text: item.name,
            status: 'none'
          }
        })
        return channelObj
      }
    },
    {
      title: '推广页面',
      dataIndex: 'page_type',
      align: 'center',
      width: 100,
      valueEnum: promotionPageMap
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      valueEnum: {
        1: {
          text: '使用中',
          status: 'Success'
        },
        2: {
          text: '已停用',
          status: 'Error'
        }
      }
    },
    {
      title: '点击量',
      dataIndex: 'click_num',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '点击用户',
      dataIndex: 'click_user',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '注册用户',
      dataIndex: 'grant_num',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '转化订单',
      dataIndex: 'trans_num',
      width: 100,
      align: 'center',
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('order', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.trans_num}
          </div>
        )
      }
    },
    {
      title: '转化率',
      dataIndex: 'conversion_rate',
      align: 'center',
      hideInSearch: true,
      width: 100
    },
    {
      title: '成交订单',
      dataIndex: 'ship_total_order',
      align: 'center',
      hideInSearch: true,
      width: 100,
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('deal', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.ship_total_order}
          </div>
        )
      }
    },
    {
      title: '订单成交率',
      dataIndex: 'transaction_conversion_rate',
      align: 'center',
      width: 100,
      hideInSearch: true,
      hideInTable: currentIsOpen
    },
    {
      title: '成交用户数',
      dataIndex: 'transaction_users_number ',
      align: 'center',
      width: 100,
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('deal_user', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.transaction_users_number}
          </div>
        )
      }
    },
    {
      title: '用户成交率',
      dataIndex: 'transaction_user_rate',
      align: 'center',
      hideInSearch: true,
      width: 100
    },
    {
      title: '逾期订单',
      dataIndex: 'overdue_order',
      align: 'center',
      width: 100,
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('overdue_order', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.overdue_order}
          </div>
        )
      }
    },
    {
      title: '逾期率',
      dataIndex: 'overdue_rate',
      align: 'center',
      width: 100,
      hideInSearch: true
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      align: 'center',
      width: 200,
      valueType: 'dateTimeRange',
      search: {
        transform: value => {
          return {
            start_time: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end_time: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      },
      render: (_, row) => {
        return <div>{row.created_at ? row.created_at : '-'}</div>
      }
    },
    {
      title: '创建人',
      width: 120,
      align: 'center',
      dataIndex: 'operator_name'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      width: 300,
      hideInSearch: true
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      fixed: 'right',
      align: 'right',
      render: (_, row) => {
        const statusObj = {
          1: {
            text: '停用',
            color: '#F55107',
            confirm: '停用后链接将无法打开（启用后可恢复），是否确认停用？'
          },
          2: {
            text: '启用',
            color: '#3BC277',
            confirm: '确定启用吗?'
          }
        }

        return (
          <Space>
            <Button type='link' onClick={() => handleAddAndEdit('edit', row)}>
              编辑
            </Button>

            <Button type='link' onClick={() => handlePromotionLink(row)}>
              推广
            </Button>

            <Button type='link' onClick={() => handleOpenData(row)}>
              开放数据
            </Button>

            <Popconfirm title={statusObj[row.status].confirm} onConfirm={() => handleSetStatus(row)}>
              <Button type='link' style={{ color: statusObj[row.status].color }}>
                {statusObj[row.status].text}
              </Button>
            </Popconfirm>

            <Popconfirm
              title={'删除后链接将无法恢复，是否确认删除该推广活动？'}
              onConfirm={() => handleDeleteItem(row)}
            >
              <Button type='link' danger>
                删除
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  // 开放数据
  const openColumns = [
    {
      title: '推广渠道',
      dataIndex: 'plat_from',
      align: 'center'
    },
    {
      title: '点击用户数',
      dataIndex: 'click_user',
      align: 'center'
    },
    {
      title: '点击次数',
      dataIndex: 'click_num',
      align: 'center'
    },
    {
      title: '注册用户数',
      dataIndex: 'grant_num',
      align: 'center'
    },
    {
      title: '订单量',
      dataIndex: 'trans_num',
      align: 'center',
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('order', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.trans_num}
          </div>
        )
      }
    },
    {
      title: '转换率',
      dataIndex: 'conversion_rate',
      align: 'center'
    },
    {
      title: '成交用户数',
      dataIndex: 'transaction_users_number',
      align: 'center',
      render: (_, row) => {
        return (
          <div onClick={() => handleCheckDetail('deal_user', row)} style={{ color: '#4676FB', cursor: 'pointer' }}>
            {row.transaction_users_number}
          </div>
        )
      }
    },
    {
      title: '用户成交率',
      dataIndex: 'transaction_user_rate',
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      align: 'center',
      render: (_, row) => {
        return <div>{row.created_at ? row.created_at : '-'}</div>
      }
    }
  ]

  const columns = currentIsOpen ? openColumns : originColumns

  // 商品列表
  const selectGoodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
      render: (text, record) => (
        <Space>
          <Image width={48} src={record.goods_cover_url} />
          <a onClick={() => goProduct(3, record.id, record.merchant_id)}>{text}</a>
        </Space>
      )
    },
    {
      title: '商品ID',
      dataIndex: 'id',
      width: 60,
      hideInTable: true
    },
    {
      title: '买断价',
      dataIndex: 'buyout_price_range',
      hideInSearch: true,
      width: 140
    },
    {
      title: '租赁信息',
      dataIndex: 'rent_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('rent')) {
          const { deposit, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                押金：{deposit[0]}~{deposit[1]}
              </div>
              <div>
                租期：{periods[0]}~{periods[1]}
              </div>
              <div>
                期数：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                每期租金：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '买卖信息',
      dataIndex: 'buy_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('buy')) {
          const { first_pay_range, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                首付款：{first_pay_range[0]}~{first_pay_range[1]}
              </div>
              <div>
                尾期：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                期数：{periods[0]}~{periods[1]}
              </div>
              <div>
                每期尾款：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '物流配送',
      dataIndex: 'delivery_type_names',
      width: 120,
      hideInSearch: true,
      render: text => (
        <>
          {text.map(i => (
            <div key={i}>{i}</div>
          ))}
        </>
      )
    },
    {
      title: '归属店铺',
      dataIndex: 'shop_name',
      valueType: 'select',
      valueEnum: new Map(shopList),
      width: 120
    },
    {
      title: '物流配送',
      dataIndex: 'ship_type',
      hideInTable: true,
      valueType: 'select',
      valueEnum: new Map(shipList),
      width: 120
    },
    {
      title: '展示渠道',
      width: 100,
      dataIndex: 'plts',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: new Map(searchChannel),
      render: (text, record) => record.plts.map((i, index) => <div key={index}>{i}</div>)
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      width: 220
    },
    {
      title: '商品详情',
      key: 'option',
      width: 80,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <a
            key='check'
            onClick={() => {
              goProduct(3, row.id, row.merchant_id)
            }}
          >
            查看详情
          </a>
        )
      }
    }
  ]

  return (
    <>
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const filters = {
            promotion_name: params.promotion_name,
            channel: params.channel,
            page_type: params.page_type,
            status: params.status,
            start_time: params.start_time,
            end_time: params.end_time
          }

          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...filters
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          let res = null

          if (currentIsOpen) {
            let tempRes = await GetPromotionInfo({ id: pageId })
            res = Array.isArray(tempRes) ? tempRes : [tempRes]
          } else {
            let tempRes = await PromotionList(param)
            res = tempRes || []
          }

          return {
            data: currentIsOpen ? res : res.data,
            success: true,
            total: currentIsOpen ? 10 : res.total
          }
        }}
        pagination={
          currentIsOpen
            ? false
            : {
                pageSize: pageSize,
                current: currentPage,
                showSizeChanger: true
              }
        }
        headerTitle={
          currentIsOpen ? (
            '投放数据'
          ) : (
            <Button
              icon={<PlusOutlined />}
              onClick={() => handleAddAndEdit('add')}
              key={Math.random().toString()}
              type='primary'
            >
              新增推广链接
            </Button>
          )
        }
        scroll={{ x: 'max-content' }}
        rowKey='id'
        columns={columns}
        search={
          currentIsOpen
            ? false
            : {
                defaultCollapsed: false,
                labelWidth: 'auto',
                span: 8
              }
        }
      />
      <Drawer title={drawerData.title} onClose={onDrawerChange} open={drawerOpen} width={'80%'} destroyOnClose={true}>
        <PromotionOrderDetails data={drawerData} />
      </Drawer>

      <PromotionLinkModal
        userParams={userParams}
        isModalOpen={promotionModalOpen}
        setIsModalOpen={setPromotionModalOpen}
      />

      {/*添加商品抽屉*/}
      <Drawer
        title='选择商品'
        placement='right'
        zIndex='99999'
        onClose={triggerGoodsDrawer}
        open={goodsDrawerFlag}
        width={'80%'}
        destroyOnClose
        footer={
          <div>
            <Space>
              <Button onClick={triggerGoodsDrawer}>取消</Button>
              <Button type='primary' disabled={!drawerSelectGoods || !drawerSelectGoods.length} onClick={handleDisplay}>
                确认
              </Button>
            </Space>
          </div>
        }
      >
        <Alert message='仅可以选择展示中的商品。' type='info' showIcon />
        <ProTable
          search={{
            defaultCollapsed: false,
            labelWidth: 75,
            span: 8
          }}
          actionRef={selectGoodsTableRef}
          // 隐藏多选工具栏
          tableAlertRender={false}
          tableAlertOptionRender={false}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: drawerSelectGoods.map(i => i.id),
            onChange: (keys, rows) => {
              setDrawerSelectGoods(rows)
            }
          }}
          request={async params => {
            const param = {
              get_online_goods: 1,
              page: params.current,
              page_size: params.pageSize,
              goods_name: params.goods_name,
              id: params.id,
              merchant_id: params.shop_name,
              ship_type: params.ship_type,
              plt: tabObj[tempChannel]
            }
            const res = await PlatformGoodsList(param)
            return {
              data: res.data,
              success: true,
              total: res.total
            }
          }}
          pagination={{
            pageSize: 10
          }}
          options={false}
          rowKey='id'
          columns={selectGoodsColumns}
          scroll={{ x: 'max-content' }}
        />
      </Drawer>
    </>
  )
}
